from datetime import timedelta
import random

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.db.models import F
from django.urls import reverse
from django.utils import timezone

from .models import Question, Choice, User
from .forms import VoteForm, SignupForm, LoginForm


def index(request):
    now = timezone.now()
    qs = Question.objects.filter(pub_date__lt=now)[:5]
    context = {'latest_questions': qs}
    return render(request, 'polls/index.html', context=context)


def detail(request, pk):
    now = timezone.now()
    q = get_object_or_404(Question, pk=pk, pub_date__lt=now)
    return render(request, 'polls/detail.html', context={'question': q})


def results(request, pk):
    q = get_object_or_404(Question, pk=pk)
    return render(request, 'polls/results.html', context={'question': q})


def vote(request, pk):
    if request.method == 'POST':
        form_data = {'question': pk}
        form_data.update(request.POST)
        form = VoteForm(form_data)
        if form.is_valid():
            cpk = form.cleaned_data['choice']
            Choice.objects.filter(pk=cpk).update(votes=F('votes')+1)
            results_url = reverse('polls:results', kwargs={'pk': pk})
            return HttpResponseRedirect(redirect_to=results_url)
    back_url = request.META.get('HTTP_REFERER')
    if back_url:
        return HttpResponseRedirect(redirect_to=back_url)
    else:
        return HttpResponse('Invalid operation', status=400)


def signup(request):
    error_msg = ''
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            password = form.cleaned_data['password']
            if User.objects.filter(name=name).count():
                error_msg = 'user %s exists' % name
            else:
                User.objects.create(name=name, password=password)
                login_url = reverse('polls:login')
                return HttpResponseRedirect(redirect_to=login_url)
    else:
        form = SignupForm()
    context = {'form': form, 'errmsg': error_msg,
               'title': 'Sign Up', 'submit_value': 'Sign Up'}
    return render(request, 'polls/signup.html', context=context)


def login(request):
    error_msg = ''
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            password = form.cleaned_data['password']
            if User.objects.filter(name=name, password=password).count():
                index_url = reverse('polls:index')
                response = HttpResponseRedirect(redirect_to=index_url)
                expires = timezone.now() + timedelta(days=1)
                session_data = '%s\n%s' % (name, expires.strftime('%s'))
                sessionid = str(random.randint(0, 100000))
                request.session[sessionid] = session_data
                response.set_cookie('session_id', sessionid)
                return response
            else:
                error_msg = 'login failed'
    else:
        form = LoginForm()
    context = {'form': form, 'errmsg': error_msg,
               'title': 'Login', 'submit_value': 'Login'}
    return render(request, 'polls/login.html', context=context)


def logout(request):
    login_url = reverse('polls:login')
    response = HttpResponseRedirect(redirect_to=login_url)
    response.set_cookie('login', '0')
    return response
